package com.lkd.controller;

import com.lkd.dto.SkuDto;
import com.lkd.result.PageBean;
import com.lkd.result.Result;
import com.lkd.service.SkuService;
import com.lkd.utils.OssTemplate;
import com.lkd.vo.SkuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @className: SkuController
 * @description:
 * @author: InnovatorX
 * @date: 2024/5/28 14:07
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/vm-service/sku")
public class SkuController extends Result {
    @Autowired
    private SkuService skuService;
    @Autowired
    private OssTemplate aliyunOSSService;
    /**
     * 图片上传
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    @PostMapping("/fileUpload")
    public Result<String> uploadImage(MultipartFile fileName) throws IOException {
        /**
         * 将文件上传到阿里云OSS服务。
         * @param fileName 原始文件名，来自于上传文件的表单字段。
         * @param fileInputStream 文件的输入流，用于读取文件内容。
         * @return 返回上传后的文件在OSS服务中的存储路径。
         */
        String store = aliyunOSSService.upload(fileName.getOriginalFilename(), fileName.getInputStream());
        return success(store);
    }

    /**
     * 新增商品
     *
     * @param dto
     * @return
     */
    @PostMapping
    public Result saveSku(@RequestBody SkuDto dto) {
        skuService.saveSku(dto);
        return success();
    }

    /**
     * 商品搜索
     *
     * @param skuName
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/search")
    public Result<SkuDto> search(
            @RequestParam(name = "skuName", required = false) String skuName,
            @RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        // 调用业务层方法
        PageBean<SkuVo> pageBean = skuService.search(skuName, pageIndex, pageSize);
        return success(pageBean);
    }

    /**
     * 查询某商品ID
     * @param skuId
     * @return
     */
    @GetMapping("/{skuId}")
    public Result<SkuVo> getById(@PathVariable("skuId") Long skuId) {
        SkuVo skuVo = skuService.getById(skuId);
        return success(skuVo);
    }
    /**
     * 修改商品
     */
    @PutMapping
    public Result update(@RequestBody SkuDto dto) {
        skuService.update(dto);
        return success();
    }
}
